package com.aifeng.hassan_food.mine

import android.os.Bundle
import android.text.InputFilter
import android.view.View
import com.aifeng.base.BaseActivity
import com.aifeng.base.addItems
import com.aifeng.common_ui.base.getColorEx
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.*
import com.aifeng.hassan_food.R
import com.aifeng.model.AreaData
import com.aifeng.model.CommonData
import com.aifeng.utils.DialogHelper.showCityDialog
import com.aifeng.utils.DialogHelper.showHintDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByNoError
import com.aifeng.viewmodel.AdressViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.activity_address_add.*
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class AddressAddActivity : BaseActivity() {

    private var mProvince = ""
    private var mCity = ""
    private var mArea = ""
    private lateinit var mData: CommonData
    private val areaList = ArrayList<AreaData>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_address_add)
        mData = (intent.getSerializableExtra("data") ?: CommonData()) as CommonData

        if (mData.id.isEmpty()) initTitle(title = "新增收货地址")
        else {
            initTitle(title = "编辑收货地址", name = "保存")
            tvRight?.setTextColor(getColorEx(R.color.colorAccent))
            bt_save.gone()
            adress_del.visible()
            initData()
        }
    }

    override fun getViewModel() = getViewModel<AdressViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        @Suppress("DEPRECATION")
        val drawable = resources.getDrawable(R.drawable.ic_adress_selector)
        drawable.setBounds(0, 0, dp2px(15f), dp2px(15f))
        adress_check.setCompoundDrawables(drawable, null, null, null)

        adress_name.filters = arrayOf<InputFilter>(NameLengthFilter(20))

        adress_area.oneClick {
            if (areaList.isEmpty()) {
                getViewModel().getAreaList(this)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribe {
                        areaList.addItems(it)
                        if (areaList.isNotEmpty()) showDialog()
                    }
            } else showDialog()
        }

        adress_del.oneClick {
            showHintDialog(
                title = "删除地址",
                hint = "确定要删除当前收货地址？",
                sure = "删除"
            ) {
                getViewModel().delArea(mData.id)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            LiveEventBus.get("adress").post("refresh")

                            val items = listOf("delete", mData.id)
                            LiveEventBus.get("adressConfirm").post(items.joinToString(","))

                            ActivityStack.screenManager.popActivities(this::class.java)
                        }
                    )
            }
        }
    }

    private fun initData() {
        adress_name.setText(mData.receiver)
        adress_phone.setText(mData.phone)
        adress_detail.setText(mData.address)
        adress_check.isChecked = mData.type == "1"

        mProvince = mData.pro
        mCity = mData.city
        mArea = mData.area
        adress_area.setRightString("$mProvince $mCity $mArea")
    }

    private fun showDialog() {
        showCityDialog(
            list = areaList,
            defaultProvince = mProvince,
            defaultCity = mCity,
            defaultArea = mArea,
            listener = { province, city, area, _, _, _ ->
                mProvince = province
                mCity = city
                mArea = area
                adress_area.setRightString("$mProvince $mCity $mArea")
            }
        )
    }

    override fun doClick(v: View) {
        super.doClick(v)
        when (v.id) {
            R.id.tv_nav_right, R.id.bt_save -> {
                when {
                    adress_name.text.isBlank() -> {
                        adress_name.requestFocus()
                        toast("请填写收货人")
                        return
                    }
                    adress_phone.text.isEmpty() -> {
                        adress_phone.requestFocus()
                        toast("请填写收货人电话")
                        return
                    }
                    mProvince.isEmpty()
                            || mCity.isEmpty()
                            || mArea.isEmpty() -> {
                        toast("请选择所在地区")
                        return
                    }
                    adress_detail.text.isBlank() -> {
                        adress_detail.requestFocus()
                        toast("请输入详细地址信息")
                        return
                    }
                    !adress_phone.text.isMobile() -> {
                        adress_phone.requestFocus()
                        toast("请输入正确的手机号码")
                        return
                    }
                }

                when (v.id) {
                    R.id.bt_save -> {
                        getViewModel().addArea(
                            "userid" to getString("userId"),
                            "receiver" to adress_name.textString(),
                            "phone" to adress_phone.textString(),
                            "pro" to mProvince,
                            "city" to mCity,
                            "area" to mArea,
                            "address" to adress_detail.textString(),
                            "type" to if (adress_check.isChecked) "1" else "0"
                        ).bindLifeCycle(getLifecycleOwner())
                            .subscribeByNoError(
                                event = getViewModel(),
                                onSuccess = {
                                    LiveEventBus.get("adress").post("refresh")
                                    LiveEventBus.get("adressConfirm").post("add")
                                    ActivityStack.screenManager.popActivities(this::class.java)
                                }
                            )
                    }
                    R.id.tv_nav_right -> {
                        getViewModel().editArea(
                            "id" to mData.id,
                            "userid" to getString("userId"),
                            "receiver" to adress_name.textString(),
                            "phone" to adress_phone.textString(),
                            "pro" to mProvince,
                            "city" to mCity,
                            "area" to mArea,
                            "address" to adress_detail.textString(),
                            "type" to if (adress_check.isChecked) "1" else "0"
                        ).bindLifeCycle(getLifecycleOwner())
                            .subscribeByNoError(
                                event = getViewModel(),
                                onSuccess = {
                                    LiveEventBus.get("adress").post("refresh")

                                    val mAdress = adress_detail.textString()
                                    val items = listOf(
                                        "modify",
                                        mData.id,
                                        adress_name.textString(),
                                        adress_phone.textString(),
                                        when {
                                            mProvince in mAdress
                                                    || mCity in mAdress
                                                    || mArea in mAdress -> mAdress
                                            else -> mProvince + mCity + mArea + mAdress
                                        }
                                    )
                                    LiveEventBus.get("adressConfirm").post(items.joinToString(","))

                                    ActivityStack.screenManager.popActivities(this::class.java)
                                }
                            )
                    }
                }

            }
        }
    }

}
